const request = require('superagent')

// 自定义判断元素类型JS
const toType = (obj) => {
  return {}.toString
    .call(obj)
    .match(/\s([a-zA-Z]+)/)[1]
    .toLowerCase()
}
// 参数过滤函数
const filterNull = (o) => {
  if (toType(o) !== 'object') return o
  for (var key in o) {
    if (o[key] === null) {
      delete o[key]
    }
    if (toType(o[key]) === 'string') {
      o[key] = o[key].trim()
      if (o[key].length === 0) {
        delete o[key]
      }
    }
  }
  return o
}

let callbacks = []
// let ossResponsed = false // oss
let ossResponsed = true

const httpBase = (method, url, params, success, failure) => {
  let call = () => {
    var r = request(method, url)
    if (params) {
      // params = filterNull(params)
      if (method === 'POST' || method === 'PUT') {
        if (toType(params) === 'formdata') {
          // r.responseType('blob')
          // r.set('Content-Type', 'multipart/form-data')
          r.send(params)
        } else if (toType(params) === 'object') {
          // params = JSON.stringify(params)
          // params = getFormData(params)
          r.set('Content-Type', 'application/json; charset=utf-8')
          r.send(params)
        } else {
          r.set('Content-Type', 'application/json; charset=utf-8')
          r.send(params)
        }
        // console.log(params)
        // r = r.send(params)
      } else if (method === 'GET' || method === 'DELETE') {
        r.set('Content-Type', 'application/json; charset=utf-8')
        r.query(params)
      }
    }
    // var router = this.$router
    r.end((err, res) => {
      if (err) {
        //  Message.error('系统错误：CODE:' + res.status)
        Toast({ mes: '系统错误' + err, timeout: 2000, icon: 'error' })
      }
      if (parseInt(res.status) === 200) {
        if (success) {
          if (res.body) {
            if (res.body.code === '-5000') {
              Toast({ mes: '系统内部错误', timeout: 1500, icon: 'error' })
            }
            if (res.body.code === '404') {
              Toast({ mes: '404错误', timeout: 1500, icon: 'error' })
            }
            if (res.body.code !== '0' && res.body.code !== '-5000' && res.body.code !== '404' && res.body.msg && !params.callback) {
              Toast({ mes: res.body.msg, timeout: 1500, icon: 'error' })
            }
            success(res.body || res.text)
          } else {
            success(res)
          }
        }
      } else {
        if (failure) {
          failure(res.body || res.text)
        } else {
          if (res.body.code === '-5000') {
            Toast({ mes: '系统内部错误', timeout: 1500, icon: 'error' })
          } else if (res.body.code === '404') {
            Toast({ mes: '404错误', timeout: 1500, icon: 'error' })
          } else {
            Toast({ mes: JSON.stringify(res.body.msg), timeout: 1500, icon: 'error' })
          }
          // window.alert('error: ' + JSON.stringify(res.body))
        }
      }
    })
  }
  ossResponsed ? call() : callbacks.push(call)
}

let server = ''
let http = {}

http.get = (url, params, success, failure) => {
  return httpBase('GET', server + url, params, success, failure)
}

http.post = (url, params, success, failure) => {
  return httpBase('POST', server + url, params, success, failure)
}

http.postString = (url, params, success, failure) => {
  return httpBase('POST', server + url, JSON.stringify(params), success, failure)
}

http.postData = (url, params, success, failure) => {
  let data = new FormData()
  for (var x in params) {
    data.append(x, params[x])
  }
  return httpBase('POST', server + url, data, success, failure)
}

http.upload = (url, params, success, failure) => {
  var post = true
  var data = new window.FormData()
  if (params.uploadIDfile) {
    var obj = document.getElementById(params.uploadIDfile)
    var file = obj.files[0]
    // 验证文件格式
    if (file.type !== 'image/png' && file.type !== 'image/jpeg' && file.type !== '') {
      alert('目前只支持上传png，jpg格式图片')
      post = false
      return false
    }
    // 验证文件大小
    if (params.maxsize) {
      if (obj.size > params.maxsize) {
        post = false
        alert('上传文件不能大于' + parseInt(params.maxsize / 1024) + 'KB')
        return false
      }
    }
    data.append(params.uploadID, file)
    obj.value = ''
  }
  return post && httpBase('POST', server + url, data, success, failure)
}

http.put = (url, params, success, failure) => {
  return httpBase('PUT', server + url, params, success, failure)
}

http.delete = (url, params, success, failure) => {
  return httpBase('DELETE', server + url, params, success, failure)
}

http.install = (Vue, options) => {
  Vue.prototype.$http = http
}

module.exports = {
  http
}